﻿using System;
using System.IO;
using System.Text;
using System.Web;
using System.Net;
namespace HuoTu.Common
{
    public class SysHtml
    {
        #region 模板操作
        /// <summary>
        /// 模板读取
        /// </summary>
        /// <param name="template">模板文件路径</param>
        /// <returns></returns>
        public static string ReadTemplate(string template)
        {
            string str = string.Empty;
            if (SysFile.CheckFile(template))
            {
                // 读取模板文件
                StreamReader sr = new StreamReader(SysString.ChangePath(template), UnicodeEncoding.GetEncoding("UTF-8"));
                try
                {
                    str = sr.ReadToEnd();
                }
                finally
                {
                    sr.Close();
                }
            }
            else
            {
                str = "模板文件未找到！";
            }
            return str;
        }
        /// <summary>
        /// 模板读取
        /// </summary>
        /// <param name="template">模板文件路径</param>
        /// <returns></returns>
        public static string ReadTemplateGb2312(string template)
        {
            string str = string.Empty;
            if (SysFile.CheckFile(template))
            {
                // 读取模板文件
                StreamReader sr = new StreamReader(SysString.ChangePath(template), UnicodeEncoding.GetEncoding("Gb2312"));
                try
                {
                    str = sr.ReadToEnd();
                }
                finally
                {
                    sr.Close();
                }
            }
            else
            {
                str = "模板文件未找到！";
            }
            return str;
        }

        /// <summary>
        /// 替换模板中的标签
        /// </summary>    
        /// <param name="str">读取模版的内容</param>
        /// <param name="tag">标签名称</param>
        /// <param name="text">要被替换的标签的内容：Html代码</param>
        /// <returns></returns>
        public static string ReplaceHtml(string str, string tag, string text)
        {
            // 替换内容
            // 这时,模板文件已经读入到名称为str的变量中了
            str = str.Replace(tag, text); //模板页中的标签被替换
            return str;
        }

        #endregion

        #region 生成静态页
        /// <summary>
        /// 生成静态页
        /// </summary>
        /// <param name="str">读取模版的内容</param>
        /// <param name="toFile">生成的最终文件</param>
        /// <returns></returns>
        public static bool CreateHtml(string str, string toFile)
        {
            // 写文件
            Encoding code = Encoding.GetEncoding("UTF-8");
            string path = HttpContext.Current.Server.MapPath(toFile);
            StreamWriter sw = null;
            try
            {
                sw = new StreamWriter(path, false, code);
                sw.Write(str);
                sw.Flush();
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write(ex.Message);
                HttpContext.Current.Response.End();
            }
            finally
            {
                sw.Close();
            }
            return true;

        }
        /// <summary>
        /// 生成静态页(Gb2312)
        /// </summary>
        /// <param name="str">读取模版的内容</param>
        /// <param name="file">生成的最终文件</param>
        /// <returns></returns>
        public static bool CreateHtmlGb2312(string str, string file)
        {
            // 写文件
            Encoding code = Encoding.GetEncoding("Gb2312");
            string path = HttpContext.Current.Server.MapPath(file);
            StreamWriter sw = null;
            try
            {
                sw = new StreamWriter(path, false, code);
                sw.Write(str);
                sw.Flush();
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write(ex.Message);
                HttpContext.Current.Response.End();
            }
            finally
            {
                sw.Close();
            }
            return true;

        }
        /// <summary>
        /// 将Html代码写入文件中
        /// </summary>
        /// <param name="str">Html代码值</param>
        /// <param name="strToFilePath">要保存的文件目的文件夹</param>
        /// <param name="fileName">要保存的文件名称</param>
        public static void CreateHtml(string str, string strToFilePath, string fileName)
        {
            string _filePath = SysString.ChangePath(strToFilePath);
            //判断新地址的文件夹是否存在(不存在则创建)
            if (!SysFile.CheckFolder(_filePath))
                SysFile.CreateFolder(_filePath);

            StreamWriter sw = new StreamWriter(_filePath + fileName, false, UnicodeEncoding.GetEncoding("utf-8"));
            try
            {
                sw.Write(str);
                sw.Flush();
            }
            finally
            {
                sw.Close();
            }
        }
        /// <summary>
        /// 将Html代码写入文件中(Gb2312)
        /// </summary>
        /// <param name="str">Html代码值</param>
        /// <param name="strToFilePath">要保存的文件目的文件夹</param>
        /// <param name="fileName">要保存的文件名称</param>
        public static void CreateHtmlGb2312(string str, string strToFilePath, string fileName)
        {
            string _filePath = SysString.ChangePath(strToFilePath);
            //判断新地址的文件夹是否存在(不存在则创建)
            if (!SysFile.CheckFolder(_filePath))
                SysFile.CreateFolder(_filePath);

            StreamWriter sw = new StreamWriter(_filePath + fileName, false, UnicodeEncoding.GetEncoding("Gb2312"));
            try
            {
                sw.Write(str);
                sw.Flush();
            }
            finally
            {
                sw.Close();
            }
        }

        /// <summary>
        /// 根据指定的网址路径生成静态页面[移到相对路径进行处理]
        /// </summary>
        /// <param name="_url">完整的网址路径文件名</param>
        /// <param name="_path">要生成的静态页路径</param>
        /// <param name="_fileName">要生成的文件名字</param>
        /// <returns></returns>
        public static bool WriteHtmlFile(string _url, string _path, string _fileName)
        {
            string _strUrl = "";
            StreamReader reader = null;
            Stream respStream = null;
            try
            {
                //Uri uri = new Uri(_url, true);
                System.Net.HttpWebRequest wReq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(_url);
                //wReq.Timeout = 300000;
                //wReq.Method = "GET";
                //wReq.ContentType = "*/*";
                System.Net.HttpWebResponse wResp = (System.Net.HttpWebResponse)wReq.GetResponse();
                respStream = wResp.GetResponseStream();
                reader = new StreamReader(respStream, Encoding.GetEncoding("utf-8"));
                _strUrl = reader.ReadToEnd();
            }
            catch (Exception ex)
            {
                //HttpContext.Current.Response.Write(ex.Message);
                //HttpContext.Current.Response.End();
                return false;
            }
            finally
            {
                respStream.Close();
                reader.Close();
            }

            StreamWriter sw = null;
            Encoding code = Encoding.GetEncoding("gb2312");
            try
            {
                DirectoryInfo DI = new DirectoryInfo(_path);
                if (!DI.Exists) DI.Create();
                //FileInfo FI = new FileInfo(_path + "/" + _fileName);
                //if (!FI.Exists) FI.Create();
                //FI.Refresh();
                sw = new StreamWriter(_path + "/" + _fileName, false, code);
                sw.Write(_strUrl);
                sw.Flush();
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write(ex.Message);
                HttpContext.Current.Response.End();
                return false;
            }
            finally
            {
                if (sw != null) sw.Close();
            }
            return true;
        }
        #endregion

        #region 数据抓取
        public static string HttpWebResponse(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";
            request.KeepAlive = true;
            request.Timeout = 10000;
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (Stream stream = response.GetResponseStream())
                {
                    StreamReader streamRead = new StreamReader(stream);
                    StringBuilder strB = new StringBuilder();
                    Char[] readBuff = new Char[256];
                    int count = streamRead.Read(readBuff, 0, 256);
                    while (count > 0)
                    {
                        String outputData = new String(readBuff, 0, count);
                        strB.Append(outputData);
                        count = streamRead.Read(readBuff, 0, 256);
                    }
                    return strB.ToString();
                }
            }
        }
        #endregion
    }
}
